#!/bin/sh
# shellcheck disable=SC2016
#
# patch main.cpio of initramfs
#
{ [ $# -gt 0 ] && [ -e "$1" ]; } || {
	echo "Please specify the main.cpio of initrd."
	echo ""
	echo "Usage: sh %0 <main.cpio>"
	exit 1
}

f="$1".patched
cp "$1" "$f" || exit $?
#
b=$(grep -m1 -h -o -b -U -z -P -e '\n\s+rm -rf "\$DEBCONF_TMPDIR"\n\n' "$f" | head -n1) &&
b=${b%:*} && [ -n "$b" ] &&
printf 'chroot /root rm -fr "$DEBCONF_TMPDIR"\nexec 1>&6 6>&-\n' |
dd seek=$((b + 1)) oflag=seek_bytes of="$f" conv=notrunc 2>/dev/null
#
b=$(grep -m1 -h -o -b -U -z -P -e '\n\s+case "\$\(get_fstype \$\{devname\}\)" in\n\s+vfat\)\n' "$f" | head -n1) &&
b=${b%:*} && [ -n "$b" ] &&
printf "    %s\n" 't=$(get_fstype ${devname})' 'case "$t" in' 'vfat)' ':;;' '*)' 'grep -q -e "\<wbfstype=[^ ]*\<$t\>" /proc/cmdline ||' |
dd seek=$((b + 1)) oflag=seek_bytes of="$f" conv=notrunc 2>/dev/null
#
o=$(grep -m1 -h -o -b -U -z -P -e '\n\s+if .* zcat ' "$f" | head -n2) &&
b=${o%%:*} && [ -n "$b" ] && o=${o#*:} &&
o=$(echo "$o" | sed -e 's/    \(if .* \)zcat/\1gzip -dc/') &&
printf "%s" "$o" | dd seek="$b" oflag=seek_bytes of="$f" conv=notrunc 2>/dev/null
#
o=$(grep -m1 -h -o -b -U -z -P -e '\n\. /scripts/local\n' "$f" | head -n2) &&
b=${o%%:*} && [ -n "$b" ] && o=${o#*:} &&
i=local_premount && printf "%s\n" "$o" "$i" |
dd seek=$((b - ${#i} - 1)) oflag=seek_bytes of="$f" conv=notrunc 2>/dev/null
ls -l main.cpio "$f" && diff -a -u main.cpio "$f"
[ $? -eq 1 ]

